package wang;

public class FFT {
	public static Complex[] fft(Complex[] x) {
		int N = x.length;

		if (N == 1)
			return new Complex[] { x[0] };
		int M = N;
		if (N % 2 != 0) {
			M = 1;
			while (M < N) {
				M *= 2;
			}
			// throw new RuntimeException("N is not a power of 2");
		}

		Complex[] even = new Complex[M / 2];
		for (int k = 0; k < M / 2; k++) {
			if (2 * k >= N)
				even[k] = new Complex(0, 0);
			else
				even[k] = x[2 * k];
		}
		Complex[] q = fft(even);

		Complex[] odd = even;
		for (int k = 0; k < M / 2; k++) {
			if (2 * k + 1 >= N)
				odd[k] = new Complex(0, 0);
			else
				odd[k] = x[2 * k + 1];
		}
		Complex[] r = fft(odd);

		Complex[] y = new Complex[N];
		for (int k = 0; k < M / 2; k++) {
			double kth = -2 * k * Math.PI / M;
			Complex wk = new Complex(Math.cos(kth), Math.sin(kth));

			y[k] = q[k].plus(wk.times(r[k]));
			if ((k + M / 2) < N)
				y[k + M / 2] = q[k].minus(wk.times(r[k]));
			// System.out.println(y[0].re()+"+"+y[0].im());
		}

		return y;
	}
}
